
package com.kongshidian.ui;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.kongshidian.App;
import com.kongshidian.Constants;
import com.kongshidian.R;
import com.kongshidian.bean.Cart;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.bean.Product.SkuProduct;
import com.kongshidian.bean.Product.SpecificationValues;
import com.kongshidian.bean.Product.Specifications;
import com.kongshidian.bean.ProductBundle;
import com.kongshidian.bean.ProductGroup;
import com.kongshidian.bean.ProductImage;
import com.kongshidian.bean.PurchaseProduct;
import com.kongshidian.business.SpecialSaleType;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.view.AbsScrollGridView;
import com.kongshidian.ui.view.AbsViewHolderAdapter;
import com.kongshidian.ui.view.BadgeView;
import com.kongshidian.ui.view.CustomDigitalClock;
import com.kongshidian.ui.view.ViewFlow;
import com.kongshidian.util.ContextUtil;
import com.kongshidian.util.ImageUtil;
import com.kongshidian.util.PreferenceUtil;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author ghg
 *  商品详情
 */
@SuppressWarnings("deprecation")
public class ProductDetailActivity extends BaseActivity{

	private static final String TAG = "ProductDetailActivity";

	//for PRODUCTDETAILACTIVITY
	public static final String EXTRA_ID_TO_PRODUCTDETAILACTIVITY_PRODUCTID = "productID";

	//for ShopCarActivity
	public static final String EXTRA_ID_TO_SHOPCARACTIVITY_FROM = "from";

	//for SUBMITORDERACTIVITY
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_FROM = "from";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_SHOPITEMID = "shopItemId";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_SKUID = "skuId";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_SKUNAME = "skuName";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_BUY_NUMBER = "num";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_WEIGHT = "weight";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_PRICE = "price";
	public static final String EXTRA_ID_TO_SUBMITORDERACTIVITY_PROMOTION_Type = "promotionType";

	@ViewInject(id = R.id.herd_back_icon ,click = "butClick") ImageButton mBackImageButton;//back
	@ViewInject(id = R.id.shopcar_img ,click = "butClick") ImageView mImgShopcar; //shopcar
//	@ViewInject(id = R.id.detail_share_img ,click = "butClick") ImageView mImgShare; //分享
	@ViewInject(id = R.id.commodity_image ,click = "butClick") ImageView mImgCommodity; // 商品图片
	@ViewInject(id = R.id.viewflow ,click = "butClick") ViewFlow mViewflowCommodity;	//viewflow 
	@ViewInject(id = R.id.promotionTypeImage ) ImageView mImgPromotionType;  // 商品type 图片
//	@ViewInject(id = R.id.detail_love_img, click = "butClick") ToggleButton mTglLoveImg; //是否喜欢button
	//	@ViewInject(id = R.id.original_price_text ) TextView mTxtOriginalPrice;
	@ViewInject(id = R.id.total_image_txt ) TextView mTxtTotalImg; // 图片总数
	@ViewInject(id = R.id.commodity_discount_text ) TextView mDiscountText; //
	@ViewInject(id = R.id.commodity_name_text ) TextView mCommodityNameTxt;  //商品名
	@ViewInject(id = R.id.commodity_price_text ) TextView mCommodityPriceTxt; //商品价格
	@ViewInject(id = R.id.original_price_text ) TextView mCommodityOrigunalPriceTxt; //
	@ViewInject(id = R.id.buy_now_but, click = "butClick" ) Button mBuyNowBut;  //现在购买but
	@ViewInject(id = R.id.add_shopcar_but,click = "butClick" ) Button mAddToSopCarBut; //加入购物车but
//	@ViewInject(id = R.id.relat1_text2 ) TextView mSaleText;
//	@ViewInject(id = R.id.relat2_text2 ) TextView mCommentsText;
//	@ViewInject(id = R.id.relat3_text2 ) TextView mCollectionText;
	@ViewInject(id = R.id.shopcar_top_right_lin ) LinearLayout mTopRightLin;
//	@ViewInject(id = R.id.time_count_lin ) LinearLayout mTimeCountLin;
	@ViewInject(id = R.id.guess_you_like_list) Gallery mHorzontalList;
	@ViewInject(id = R.id.please_choose_specifications_relat,click = "butClick") RelativeLayout mChoiseSpecificationRelat;
	@ViewInject(id = R.id.commodity_detail_buttom_finish) RelativeLayout mCommodityDetialButtomFinishLayout;
	@ViewInject(id = R.id.commodity_detail_buttom_normal) RelativeLayout mCommodityDetialButtomNormalLayout;
	@ViewInject(id = R.id.product_information_relat,click = "butClick") RelativeLayout mProductInformationLayout;  //商品详细信息
//	@ViewInject(id = R.id.product_promotions_relat,click = "butClick") RelativeLayout mProductPromotionLayout;  //
//	@ViewInject(id = R.id.product_review_relat,click = "butClick") RelativeLayout mProReviewLayout;  //评论 
	@ViewInject(id = R.id.product_delivery_relat,click = "butClick") RelativeLayout mProDeliveryLayout; // 快递Relat
	@ViewInject(id = R.id.product_delivery_address) TextView mDeliveryAddressText;  // 
	@ViewInject(id = R.id.btn_finish) Button mBtnNotActived ;
	@ViewInject(id = R.id.specifications_text) TextView mSpeTextView1;
//	@ViewInject(id = R.id.product_promotions_bundle) TextView mProductBundleText;
//	@ViewInject(id = R.id.product_promotions_group) TextView mProductGroupText;
//	@ViewInject(id = R.id.product_time_text) TextView mProductTimeText;


	private String mCurrentProductId; //Current Product ID
	private SpecialSaleType mSaleType = SpecialSaleType.NA; //Special Sale Type
	private String ImagePath;  
	private String CommodityName; //Product Name
	private FinalDb db;  
	private Product mProduct = null;  //Current product
	private String[] mCurrentProductImages;  //Product Images Path Saving...


	private BadgeView badge;  
	private Cart mCart; //Current Cart ...
	private int mCurrentBuyNumber = 1; //Current Buy Count that buyer need. 

	private SizeGridAdapter mSizeGridAdapter;
	private ProductHorizontalAdapter mProductHorizontalAdapter;

	private long skuId ;
	private int skuWeight;
	private float skuPrice;	
	private List<Product> mProducts;
	public static List<ProductBundle> mProductBundles = new ArrayList<ProductBundle>();
	public static List<ProductGroup> mProductGroups = new ArrayList<ProductGroup>();

	private MyHandler mHandler = new MyHandler(this);; //UI Handler
	
	private boolean canBuy = true;
	

	//------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_product_datail);
		FinalActivity.initInjectedView(this);
		
		db = ((App) getApplication()).finalDb;

		mCurrentProductId = getIntent().getStringExtra(EXTRA_ID_TO_PRODUCTDETAILACTIVITY_PRODUCTID);
		mSaleType = (SpecialSaleType)getIntent().getSerializableExtra("saleType");
//		mCommodityOrigunalPriceTxt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		initBadge();
		initHorzontalList();
		//updateUI(); //即将特卖，历史特卖数据更新UI

		//Get the Server Data ....
		getProductByIdAsync(mCurrentProductId);
//		doAddClickHitAsync();
//		getRecommendListAsync();			


	}


	@Override
	protected void onResume() {
		super.onResume();
		updateBadge();
	}


	@Override
	protected void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}




	//Load Server Data Async ..................................
	/** 根据商品推荐 */
	private void getRecommendListAsync() {

		new Thread(){
			public void run() {
				try {
					PageEntity<Product> mEntity = WebClient.getInstance(ProductDetailActivity.this).getRecForProduct(mCurrentProductId);
					mProducts = mEntity.getContent();
					
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mProducts = null;
					else
						e.printStackTrace();
				}
				mHandler.sendEmptyMessage(3);
			};
		}.start();

	}

	private void doAddClickHitAsync() {
		new Thread(){
			public void run() { 
				try {
					//增加点击量
					WebClient.getInstance(ProductDetailActivity.this).doHit(mCurrentProductId);
				} catch (WebException e) {
					Log.w(TAG, e.toString());
					e.printStackTrace();
				}catch (Exception e) {
					Log.w(TAG, e.toString());
				}
			};
		}.start();
	}


	private void getProductByIdAsync(final String productId2) {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					mProduct = WebClient.getInstance(ProductDetailActivity.this).product( mCurrentProductId);

					dismissLoadingDialog();
					mHandler.sendEmptyMessage(0);

				} catch (WebException e) {
					Log.w(TAG, e.toString());
					canClick(false);
					dismissLoadingDialog();
					e.printStackTrace();
				}catch (Exception e) {
					Log.w(TAG, e.toString());
				}
			};
		}.start();
	}





	//UI Event ---------------------------------------

	public void butClick(View v){
		
		//点击关注----
//		if (v == mTglLoveImg) {
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
//					try {
//						WebClient client = WebClient.getInstance(ProductDetailActivity.this);
//						if (mTglLoveImg.isChecked()) {		// 关注
//							client.favoriteAdd(Long.parseLong(mCurrentProductId));
//							App.showShortToast(R.string.has_favorrites);
//						}else{ 							// 取消关注
//							client.favoriteDelete(Long.parseLong(mCurrentProductId));
//							App.showShortToast(R.string.cancelled_collection);
//							setResult(RESULT_OK);
//						}
//					} catch (NumberFormatException | WebException e) {
//						
//						if("shop.common.unauthorized".equals(((WebException) e).getStatusCode())){
//							mHandler.sendEmptyMessage(4);
//							ContextUtil.startActivityForResult(ProductDetailActivity.this, LoginActivity.class,200);
//							App.showShortToast(R.string.please_login_too);
//						}else {
//							Log.w(TAG, e.toString());
//							e.printStackTrace();
//						}
//
//					}catch (Exception e) {
//						App.showShortToast(R.string.error_msg);
//					}
//				}
//			}).start();
//		}
		//返回按钮
		if( v == mBackImageButton){
			finish();
		}
		//去购物车
		if( v == mImgShopcar){
			Intent intent = new Intent(this, ShopCarActivity.class);
			intent.putExtra(EXTRA_ID_TO_SHOPCARACTIVITY_FROM, "ProductDetailActivity");
			startActivity(intent);
		}
		//分享
//		if( v == mImgShare){
//			doShareSomething();
//		}
		//看图
		if( v == mImgCommodity){

			ImageUtil.imageBrower(ProductDetailActivity.this,0, mCurrentProductImages);
			App.showShortToast("商品图片");
		}
		//立即购买
		if( v == mBuyNowBut ){
			new MyPopupWindow(ProductDetailActivity.this,mBuyNowBut,"buy");//buy为立即购买，add为加入购物车,choise为选择
			
			if( !canBuy ){
				App.showShortToast(R.string.product_cannot_buy);
				return;
			}
			getSkuId();
			toSubmitOrderActivity(skuId,mCurrentBuyNumber,skuWeight,skuPrice);
		}
		// 加入购物车
		if( v == mAddToSopCarBut) { 		
			new MyPopupWindow(ProductDetailActivity.this,mBuyNowBut,"add");
			if( !canBuy ){
				App.showShortToast(R.string.product_cannot_buy);
				return;
			}
			getSkuId();
			 //添加购物车
			showLoadingDialog("");	
			new Thread(){
				public void run() {
					try {
						mCart = WebClient.getInstance(ProductDetailActivity.this).addProduct(skuId, mCurrentBuyNumber,mProduct.getPreferentialType());
						mHandler.sendEmptyMessage(2);
					} catch (WebException e) {
						dismissLoadingDialog();
						e.printStackTrace();

					}
				};
			}.start();
		

		}
		//选择尺码颜色
		if( v == mChoiseSpecificationRelat) { 		
			new MyPopupWindow(ProductDetailActivity.this,mBuyNowBut,"choise");

		}
		//去商品详细页
		if( v == mProductInformationLayout){
			Intent intent = new Intent(this,ProductInformationActivity.class);
			startActivity(intent);
		}
		//促销
//		if( v == mProductPromotionLayout){
//			
//			Bundle bundle = new Bundle();
//			mProductBundles = mProduct.getBundles();
//			mProductGroups = mProduct.getProductGroups();
//			
//			Gson gson = new Gson();
//			
//			bundle.putString("mProductBundles",gson.toJson(mProductBundles) );
//			bundle.putString("mProductGroups", gson.toJson(mProductGroups));
//			
//			ContextUtil.startActivity(this, ProductPromotionsActivity.class,bundle);
//		}
		//评论
//		if( v == mProReviewLayout){
//			Intent intent = new Intent(this,ProductEvaluationActivity.class);
//			intent.putExtra("proId",mCurrentProductId);
//			startActivity(intent);
//		}
		//快递 时间----
		if( v == mProDeliveryLayout ){
			Intent intent = new Intent(this, SelectAddressActivity.class);
			intent.putExtra(EXTRA_ID_TO_SHOPCARACTIVITY_FROM, "ProductDetailActivity");
			startActivity(intent);
			App.showShortToast("地址选择");
		}

	}
	
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
			//重新加载下UI
			if(200 == resultCode ){
				getProductByIdAsync(mCurrentProductId);
			}
		
		
	}


	/** 购物车数目 */
	private void updateBadge() {
		int num = PreferenceUtil.getInt(ProductDetailActivity.this, "mProductSize");
		if(num <= 0 ){
			if(badge.isShown()){
				badge.hide();
			}
		}else {
			badge.setText(num + "");
			if (!badge.isShown()) badge.show(true);
		}		

	}


	//UI Handler --------------------------------------

	private static class MyHandler extends Handler{

		// WeakReference to the outer class's instance.
		private WeakReference<ProductDetailActivity> mOuter;        

		public MyHandler(ProductDetailActivity activity) {
			mOuter = new WeakReference<ProductDetailActivity>(activity);
		}


		@Override
		public void handleMessage(Message msg) {
			ProductDetailActivity outer = mOuter.get();
			if (outer != null) {
				// Do something with outer as your wish.            	
				switch (msg.what) {
				case 0:
					outer.canClick(true);
					outer.mBuyNowBut.setBackgroundResource(R.drawable.bt_buy_now);
					outer.mAddToSopCarBut.setBackgroundResource(R.drawable.bt_add_to_shopcar);

					outer.loadPruductDetailInfo();
					break;
				case 1:
					App.showShortToast("网络链接状况差");
					//finish();
					break;
				case 2:
					outer.dismissLoadingDialog();
					PreferenceUtil.putInt(outer, "mProductSize", outer.mCart.getAllQuantity());
					ContextUtil.sendBroadcast(outer, Constants.ACTION_UPDATEBADGE);
					outer.updateBadge();
					break;
				case 3:
					outer.mProductHorizontalAdapter.update(outer.mProducts);
					outer.mHorzontalList.setSelection(1);
					break;
					
				case 4:
//					outer.mTglLoveImg.setChecked(false);
					break;
				default:
					break;
				}
			}
		}

	}

	private  TextView   mSelectText1;

	//-------------------------------------------------

	public class MyPopupWindow extends PopupWindow {

		public MyPopupWindow(Context mContext, View parent,final String method) {

			View view = View
					.inflate(mContext, R.layout.item_pay_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			view.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					dismiss();
					return false;
				}
			});
			

			TextView mproductNameText = (TextView) view.findViewById(R.id.pop_product_name); 
			TextView mproductPriceText = (TextView) view.findViewById(R.id.pop_product_price); 
			ImageView mProductImg =  (ImageView) view.findViewById(R.id.pop_product_img);
			ImageView closeImg =  (ImageView) view.findViewById(R.id.item_pop_close_img);
			ImageView reduceImg =  (ImageView) view.findViewById(R.id.pop_product_number_delete);
			ImageView addImg =  (ImageView) view.findViewById(R.id.pop_product_number_add);
			final TextView  mproSizeText = (TextView) view.findViewById(R.id.pop_product_number_count);
			final TextView  mPopNameText = (TextView) view.findViewById(R.id.item_pop_name_text);
			mSelectText1 = (TextView) view.findViewById(R.id.pay_pop_text1);
			Button  mSureBut = (Button) view.findViewById(R.id.item_pop_sure_but);

			String mProName = "";

			ImageLoader.getInstance().displayImage(ImagePath, mProductImg);
			mproductNameText.setText(mProduct.getName());
			mproductPriceText.setText("￥"+mProduct.getPrice());
			
			updateAttributeSeleteText();// 显示所选的属性

			final List<Specifications> msSpecifications = mProduct.getSpecifications();
			
			final LinearLayout mAttributeLin = (LinearLayout) view.findViewById(R.id.attribute_selete_lin);
			mAttributeLin.removeAllViews();
			
			for (int i = 0; i < msSpecifications.size(); i++) {
				final int checkId = i;
				
				final List<SpecificationValues> mSpecificationValues = msSpecifications.get(i).getSpecificationValues();
				mSpecificationValues.get(msSpecifications.get(i).getCheck()).setCheck(true);
				
				LinearLayout convertView =  (LinearLayout) LayoutInflater.from(ProductDetailActivity.this).inflate(R.layout.item_choice_attribute_pop, null);
				
				TextView mAttributeText = (TextView)convertView.findViewById(R.id.attribute_text);
				mAttributeText.setText(msSpecifications.get(i).getName());
				
				final AbsScrollGridView mAttributeGrid = (AbsScrollGridView) convertView.findViewById(R.id.attribute_detail_grid);
				
				mSizeGridAdapter = new SizeGridAdapter(ProductDetailActivity.this,R.layout.item_text_frame);
				mAttributeGrid.setAdapter(mSizeGridAdapter);
				mSizeGridAdapter.update(mSpecificationValues);
			
				
				mAttributeGrid.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent,
							View view, int position, long id) {
						for (int j = 0; j < mSpecificationValues.size(); j++) {
							mSpecificationValues.get(j).setCheck(false);
						}
						mSpecificationValues.get(position).setCheck(true);
						msSpecifications.get(checkId).setCheck(position);
						mAttributeGrid.setItemChecked(position, true);	
						mSizeGridAdapter.notifyDataSetChanged();
						
						updateAttributeText();
						updateAttributeSeleteText();
						
					}
				
				});

				mAttributeLin.addView(convertView);
				
			}
			

			//区分购买和加入购物车------------
			if( "buy".equals(method) ){
				mPopNameText.setText("立即购买");
			}else if("add".equals(method)){
				mPopNameText.setText("加入购物车");
			}else {
				mPopNameText.setText("选择属性");
			}
			
			mproSizeText.setText(mCurrentBuyNumber+"");
			
			closeImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					dismiss();	
				}
			});

			/** 增加和减少商品  */
			reduceImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					if(mCurrentBuyNumber == 1 ){
						App.showShortToast("至少买一个");
						return;
					}
					mCurrentBuyNumber --;	
					mproSizeText.setText(mCurrentBuyNumber+"");
					updateAttributeText();
				}
			});
			
			addImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					mCurrentBuyNumber ++;	
					mproSizeText.setText(mCurrentBuyNumber+"");
					updateAttributeText();
				}
			});
			//确定按钮
			mSureBut.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {

					List<String> mll = new ArrayList<String>();
					
					for (int i = 0; i < msSpecifications.size(); i++) {
						long id = msSpecifications.get(i).getSpecificationValues().get(msSpecifications.get(i).getCheck()).getId();
						mll.add(id+"");
					}

					List<String> mll1 = new ArrayList<String>();

					db.deleteAll(PurchaseProduct.class);
					
					if(null != mProduct.getItems() && mProduct.getItems().size()>0){
						for (int i = 0; i < mProduct.getItems().size(); i++) {
							mll1.clear();
							for (int j = 0; j < mProduct.getItems().get(i).getSpecificationValues().size(); j++) {
								mll1.add(mProduct.getItems().get(i).getSpecificationValues().get(j).getId()+"");
	
							}
							App.showLog("mll=="+mll);
							App.showLog("mll1=="+mll1);
							if (mll.size() == mll1.size()) {
								if( mll.size() == 0 || mll.containsAll(mll1)){
									SkuProduct msku = mProduct.getItems().get(i);
									skuId =  mProduct.getProductId(); //shop_item_id
									skuWeight = msku.getWeight();
									skuPrice = msku.getPrice();
									db.save(new PurchaseProduct(skuId, msku.getProductId(), msku.getName(),
											msku.getImage(), mCurrentBuyNumber, skuPrice));
								}
							}
						}
					}
					
					if("choise".equals(method)){

					}else if( "buy".equals(method)){//直接购买

						toSubmitOrderActivity(skuId,mCurrentBuyNumber,skuWeight,skuPrice);
						
					}else if("add".equals(method)){ //添加购物车

						showLoadingDialog("");	
						new Thread(){
							public void run() {
								try {
									mCart = WebClient.getInstance(ProductDetailActivity.this).addProduct(skuId, mCurrentBuyNumber,mProduct.getPreferentialType());
									mHandler.sendEmptyMessage(2);
								} catch (WebException e) {
									dismissLoadingDialog();
									e.printStackTrace();

								}
							};
						}.start();
					}
					dismiss();
				}
			});

		}

	}
	
	private void getSkuId(){

//		List<String> mll = new ArrayList<String>();
//		final List<Specifications> msSpecifications1 = mProduct.getSpecifications();
//		if(null!= msSpecifications1 && msSpecifications1.size()>0){
//			for (int i = 0; i < msSpecifications1.size(); i++) {
//				long id = msSpecifications1.get(i).getSpecificationValues().get(msSpecifications1.get(i).getCheck()).getId();
//				mll.add(id+"");
//			}
//		}
//
//		List<String> mll1 = new ArrayList<String>();
//
//		db.deleteAll(PurchaseProduct.class);
//		if(null != mProduct.getItems() && mProduct.getItems().size()>0){
//			for (int i = 0; i < mProduct.getItems().size(); i++) {
//				mll1.clear();
//				for (int j = 0; j < mProduct.getItems().get(i).getSpecificationValues().size(); j++) {
//					mll1.add(mProduct.getItems().get(i).getSpecificationValues().get(j).getId()+"");
//				}
//				App.showLog("mll=="+mll);
//				App.showLog("mll1=="+mll1);
//				if (mll.size() == mll1.size()) {
//					if( mll.size() == 0 || mll.containsAll(mll1)){
//						SkuProduct msku = mProduct.getItems().get(i);
//						skuId = msku.getId();
//						skuWeight = msku.getWeight();
//						skuPrice = msku.getPrice();
//						db.save(new PurchaseProduct(skuId, mProduct.getProductId(), msku.getName(),
//								mProduct.getImage(), mCurrentBuyNumber, skuPrice));
//					}
//				}
//			}
//		}
//		

		skuId =  mProduct.getProductId(); //shop_item_id
		skuWeight = mProduct.getWeight();
		skuPrice = mProduct.getPrice();
	
	}
	


	//------------------------------------------------

	public class SizeGridAdapter extends AbsViewHolderAdapter<SpecificationValues>{

		public SizeGridAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, SpecificationValues itemData) {
			TextView mTextView = (TextView) getViewFromHolder(R.id.item_frame_text);
			mTextView.setText(itemData.getName());

			if(itemData.isCheck()){
				mTextView.setTextColor(getResources().getColor(R.color.holo_title));
				mTextView.setBackgroundResource(R.drawable.text_frame_select);
			}else {
				mTextView.setTextColor(getResources().getColor(R.color.gray));
				mTextView.setBackgroundResource(R.drawable.text_frame_unselect);
			}

		}

	}


	private class ProductHorizontalAdapter extends AbsViewHolderAdapter<Product>{

		public ProductHorizontalAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {

			ImageView mImage = getViewFromHolder(R.id.product_guess_image);
			TextView mNameText = getViewFromHolder(R.id.product_guess_name);
			TextView mPriceText = getViewFromHolder(R.id.product_guess_price);

			ImageLoader.getInstance().displayImage(itemData.getImage(), mImage);
			mNameText.setText(itemData.getName());
			mPriceText.setText("￥"+itemData.getPrice());
			mPriceText.setVisibility(View.GONE);

		}
	}

	private class ImageAdapter extends BaseAdapter{
		private Context mContext;
		private String[] mImages;
		private LayoutInflater mInflater;

		public ImageAdapter(Context context,String[] images){
			this.mContext = context;
			this.mImages = images; //Several Image Path...
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return mImages.length;
		}

		@Override
		public Object getItem(int position) {
			return mImages[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_main_flow_image, null);
			}

			ImageView imgView = (ImageView) convertView.findViewById(R.id.imgView);
			if(mImages.length > 0){
				ImageLoader.getInstance().displayImage(mImages[position % mImages.length], imgView);
			}		

			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					int i = position % mImages.length;
					String url = mImages[i];
					if(url != null && url.length() != 0){
						//change ui...
					}

				}

			});
			return convertView;
		}

	}



	//------------------------------------------------

	/**
	 * Do Share 
	 */
	private void doShareSomething() {

		//showShare(false,null);

		OnekeyShare oks = new OnekeyShare();
		oks.setNotification(R.drawable.ic_launcher, ProductDetailActivity.this.getString(R.string.app_name));
		// address是接收人地址，仅在信息和邮件使用
		oks.setAddress("18812345678");
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle(getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		oks.setTitleUrl(mProduct.getPath());
		// text是分享文本，所有平台都需要这个字段
		oks.setText("来自虎丘婚纱城的分享:"+CommodityName+"详情见"+mProduct.getPath());//+Constants.IP+mProduct.getPath()
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		oks.setImagePath("");
		// imageUrl是图片的网络路径，新浪微博、人人网、QQ空间、
		// 微信的两个平台、Linked-In支持此字段
		oks.setImageUrl(ImagePath);
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl(mProduct.getPath());//Constants.IP+mProduct.getPath()
		// appPath是待分享应用程序的本地路劲，仅在微信中使用
		//oks.setAppPath(Main_BoundaryActivity.TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment(ProductDetailActivity.this.getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(ProductDetailActivity.this.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl(mProduct.getPath());
		// venueName是分享社区名称，仅在Foursquare使用
		oks.setVenueName("Southeast in China");
		// venueDescription是分享社区描述，仅在Foursquare使用
		oks.setVenueDescription("This is a beautiful place!");
		oks.setVenueName("虎丘婚纱城");
		// latitude是维度数据，仅在新浪微博、腾讯微博和Foursquare使用
		//oks.setLatitude(23.122619f);
		// longitude是经度数据，仅在新浪微博、腾讯微博和Foursquare使用
		//oks.setLongitude(113.372338f);
		// 是否直接分享（true则直接分享）
		//oks.setSilent(silent);
		//		if (platform != null) {
		//				oks.setPlatform(platform);
		//			}
		//			// 去除注释，则快捷分享的分享加过将听过OneKeyShareCallback回调
		//			oks.setCallback(new OneKeyShareCallback());
		//			oks.setShareContentCustomizeCallback(new ShareContentCustomizeDemo());

		oks.show(ProductDetailActivity.this);

	}
	//-----------------------------------------------------------

	private void canClick(boolean b){
		mBuyNowBut.setClickable(b);
		mAddToSopCarBut.setClickable(b);
	}

	private void initViewflow(){

		mViewflowCommodity.setmSideBuffer(mCurrentProductImages.length); // 实际的几张图片轮询
		mViewflowCommodity.setAdapter(new ImageAdapter(ProductDetailActivity.this,mCurrentProductImages));
	}


	private void initBadge() {
		badge = new BadgeView(this, mTopRightLin);
		badge.setBadgeBackgroundColor(Color.WHITE);
		badge.setTextColor(getResources().getColor(R.color.holo_title));
	}

	private void initHorzontalList() {
		mProductHorizontalAdapter = new ProductHorizontalAdapter(this, R.layout.item_product_detail_guess);		
		mHorzontalList.setAdapter(mProductHorizontalAdapter);
		mHorzontalList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Intent intent = new Intent(ProductDetailActivity.this,ProductDetailActivity.class);
				intent.putExtra(EXTRA_ID_TO_PRODUCTDETAILACTIVITY_PRODUCTID, String.valueOf(mProductHorizontalAdapter.getData().get(position).getId()));
				startActivity(intent);
			}

		});
	}

	private void toSubmitOrderActivity(long skuId,int num,int weight,float price) {

		Intent intent = new Intent(ProductDetailActivity.this,SubmitOrderActivity.class);
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_FROM, "ProductDetailActivity");
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_SKUID,skuId);
		//		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_SKUNAME,skuName);
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_BUY_NUMBER,num);
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_WEIGHT,weight*num);
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_PRICE,price*num+""); 
		intent.putExtra(EXTRA_ID_TO_SUBMITORDERACTIVITY_PROMOTION_Type,mProduct.getPreferentialType()); 
		startActivity(intent);
	}

	/**
	 * Load Product Detail ....
	 */
	private void loadPruductDetailInfo() {

		//图片路径
		ImagePath = mProduct.getImage();
		//商品名称
		CommodityName = mProduct.getName();

		//Previous Version : load the image
		ImageLoader.getInstance().displayImage(ImagePath, mImgCommodity);

		mCommodityNameTxt.setText(mProduct.getName());
		mCommodityPriceTxt.setText("￥"+mProduct.getPrice());

		//商品返回数据中有时带有折扣，有时没有，
		if( mProduct.getDiscount() != null && BigDecimal.valueOf(1).subtract(mProduct.getDiscount()).doubleValue() > 0){
			
			mDiscountText.setText(mProduct.getDiscount().multiply(BigDecimal.valueOf(10))+"折");
			mCommodityOrigunalPriceTxt.setText("￥"+mProduct.getReferencePrice());
			mCommodityOrigunalPriceTxt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			mCommodityOrigunalPriceTxt.setVisibility(View.VISIBLE);
		}else {
			mDiscountText.setVisibility(View.GONE);
			mCommodityOrigunalPriceTxt.setVisibility(View.GONE);
			
		}
		
		//该商品为优惠商品
//		if( mProduct.getPreferentialType() != null ){
//			mTimeCountLin.setVisibility(View.VISIBLE);
//
//			if("featuredDeal".equals(mProduct.getPreferentialType())){
//				mImgPromotionType.setImageResource(R.drawable.tm);
//			}
//			if("groupBuying".equals(mProduct.getPreferentialType())){
//				mImgPromotionType.setImageResource(R.drawable.tg);
//			}
//
//			//倒计时实现
//			long nowDate = mProduct.getNowDate();
//			long startTime = mProduct.getStartTime();
//			long endTime = mProduct.getEndTime();
//			
//			CustomDigitalClock remainTime = (CustomDigitalClock)findViewById(R.id.product_time_clock);
//			
//			/** 未开始的特卖团购*/
//			if( startTime > nowDate ){
//				
//				canBuy = false;
//				
//				mProductTimeText.setText(R.string.time_from_the_start);
//				remainTime.setEndTime(System.currentTimeMillis()+(mProduct.getStartTime()-nowDate));
//				
//			}else {
//				
//				if(nowDate > endTime  ){ // 已过期的活动
//					canBuy = false;
//					mProductTimeText.setText(R.string.time_is_expired);
//					remainTime.setVisibility(View.GONE);
//					
//				}else {
//					//一开始的特卖
//					mProductTimeText.setText(R.string.time_from_the_end);
//					remainTime.setEndTime(System.currentTimeMillis()+(mProduct.getEndTime()-nowDate));
//				}
//				
//			}
//			
//			remainTime.setClockListener(new CustomDigitalClock.ClockListener() {
//
//				@Override
//				public void timeEnd() {
//
//					//Jason add 20141127
//					//when the product is expired , the server take the special product set the normal product..
//					getProductByIdAsync(mCurrentProductId);
//
//				}
//				@Override
//				public void remainFiveMinutes() {
//					Log.d(TAG, "Five minutes are remianed ");
//				}
//			});
//
//		}else {
//			mTimeCountLin.setVisibility(View.GONE);
//		}
		
		//是否为关注商品
		
//		if(mProduct.isFavorite()){
//			mTglLoveImg.setChecked(true);
//		}else {
//			mTglLoveImg.setChecked(false);
//		}
		
		//判断有无组合购，套餐等信息
//		if( mProduct.getBundles() != null || mProduct.getProductGroups() != null ){
//			mProductPromotionLayout.setVisibility(View.VISIBLE);
//			
//			if( mProduct.getBundles() != null ){
//				mProductBundleText.setVisibility(View.VISIBLE);
//			}else {
//				mProductBundleText.setVisibility(View.GONE);
//			}
//			
//			if( mProduct.getProductGroups() != null ){
//				mProductGroupText.setVisibility(View.VISIBLE);
//			}else {
//				mProductGroupText.setVisibility(View.GONE);
//			}
//			
//		}else {
//			mProductPromotionLayout.setVisibility(View.GONE);
//		}

//		mSaleText.setText(mProduct.getSales()+"");  //销售额
//		mCommentsText.setText(mProduct.getReviewCount()+""); //评论数 
//		mCollectionText.setText(mProduct.getFavoriteCount()+"");  //点击量

		//Jason 20141128
		//According to bug 9482, remove the adv image
		List<ProductImage> productImages = mProduct.getProductImages();
		int size = productImages.size();
		mCurrentProductImages = new String[size];
		for(int i = 0 ;i < size; i++){
			mCurrentProductImages[i] = productImages.get(i).getSource();
		}
		mTxtTotalImg.setText("共" + size + "张图片");
		//initViewflow();
		
		// 遍历商品的颜色尺寸等--------------------
		updateAttributeText();
	}

	private void updateAttributeText() {
		mSpeTextView1.setText(getAttributeSeleteText()+" "+mCurrentBuyNumber+"件");
	}
	
	private void updateAttributeSeleteText() {
		mSelectText1.setText(getAttributeSeleteText());
	}


	/**
	 *  遍历获取商品当前选择的属性
	 */
	private String getAttributeSeleteText() {
		final List<Specifications> mSpecifications = mProduct.getSpecifications();
		StringBuffer strbBuffer = new StringBuffer();
		if(null != mSpecifications && mSpecifications.size()>0){
			for (int i = 0; i < mSpecifications.size(); i++) {
				int id = mSpecifications.get(i).getCheck();
				strbBuffer = strbBuffer.append(mSpecifications.get(i).getSpecificationValues().get(id).getName()+" ");
			}
		}
//		mSelectText1.setText(strbBuffer.append(" "+mCurrentBuyNumber+"件"));
//		mSpeTextView1.setText(strbBuffer.append(" "+mCurrentBuyNumber+"件"));
		return strbBuffer+"";
	}
	
	
    //---------------------------------------------------
	@SuppressWarnings("unused")
	private void updateUI(){

		if(mSaleType == null || mSaleType.equals(SpecialSaleType.NA))
			return;

		if(mSaleType.equals(SpecialSaleType.active)){

			mCommodityDetialButtomFinishLayout.setVisibility(View.GONE);
			mCommodityDetialButtomNormalLayout.setVisibility(View.VISIBLE);

		}else if(mSaleType.equals(SpecialSaleType.history)){

			mBtnNotActived.setText(getString(R.string.btn_text_finish_now));
			mCommodityDetialButtomFinishLayout.setVisibility(View.VISIBLE);
			mCommodityDetialButtomNormalLayout.setVisibility(View.GONE);
		}else if(mSaleType.equals(SpecialSaleType.next)){

			mBtnNotActived.setText(getString(R.string.btn_text_begin_sale));
			mCommodityDetialButtomFinishLayout.setVisibility(View.VISIBLE);
			mCommodityDetialButtomNormalLayout.setVisibility(View.GONE);
		}else{
			Log.w(TAG, "Go into NA status ...");

		}


	}





}
